package jgo.plugins.server;

import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;

import com.sun.net.httpserver.HttpServer;

import jgo.Context;
import jgo.JGo;
import jgo.core.ServerPlugin;

public class SimpleServerPlugin extends ServerPlugin {

	private HttpServer server;
	private CountDownLatch stopLatch;

	public SimpleServerPlugin() {
		super();
	}

	public SimpleServerPlugin(int port) {
		super(port);
	}

	@Override
	public void start(JGo jgo) {
		logger.info("Starting SimpleServerPlugin");
		try {
			server = HttpServer.create(new InetSocketAddress(port), 0);
			server.createContext("/", exchange -> {
				Context ctx = new Context(exchange);
				jgo.handleRequest(ctx);
				exchange.close();
			});
			server.setExecutor(null);
			server.start();
			logger.info("Server started on port {}", port);

			// 创建一个 CountDownLatch 来保持服务器运行
//            stopLatch = new CountDownLatch(1);

			// 添加一个关闭钩子,以便在 JVM 关闭时停止服务器
//            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//                stop();
//                stopLatch.countDown();
//            }));

			// 等待停止信号
//            stopLatch.await();
		} catch (Exception e) {
			logger.error("Failed to start or run server", e);
		}
	}

	@Override
	public void stop() {
		if (server != null) {
			logger.info("Stopping server");
			server.stop(0);
			stopLatch.countDown();
		}
	}
}